<template>
	<!-- card:属性shadow:always一直有阴影   never:没有阴影  hover:鼠标进入有阴影 -->
	<!-- 具名插槽:header，设置卡片的头部 -->
	<el-card>
		<!-- 添加品牌  导出excel  begin -->
		<el-button
			class="button"
			:icon="Plus"
			type="primary"
			@click="addTrademark"
			>添加品牌</el-button
		>
		<el-button
			type="primary"
			@click="exportData"
			>将此页面导出excel</el-button
		>
		<!-- 添加品牌  导出excel  begin -->

		<!-- 表格内容展示 begin -->
		<el-table
			border
			style="margin: 10px 0px"
			:data="records"
		>
			<!--序号 -->
			<el-table-column
				label="序号"
				width="80px"
				align="center"
				type="index"
			>
			</el-table-column>
			<!-- 品牌名称  两种写法 prop="tmName" -->
			<el-table-column
				label="品牌名称"
				prop="tmName"
			>
			</el-table-column>
			<!-- <el-table-column label="品牌名称">
				<template #="{ row, $index }">
					{{ row.tmName }}
				</template>
			</el-table-column> -->
			<!-- 品牌LOGO -->
			<el-table-column
				label="品牌LOGO"
				align="center"
			>
				<template #="{ row, $index }">
					<img
						:src="row.logoUrl"
						width="100"
					/>
				</template>
			</el-table-column>
			<!-- 操作 -->
			<el-table-column
				label="操作"
				prop=""
			>
				<template #="{ row, $index }">
					<!-- 编辑按钮 -->
					<el-button
						type="warning"
						:icon="Edit"
						size="small"
						@click="UpdateTrademark(row)"
					></el-button>
					<!-- 编辑按钮 -->
					<!-- 删除按钮 -->
					<el-popconfirm
						title="确定要删除吗?"
						@confirm="removeTradeMark(row.id)"
					>
						<template #reference>
							<el-button
								type="danger"
								size="small"
								:icon="Delete"
							></el-button>
						</template>
					</el-popconfirm>
					<!-- 删除按钮 -->
				</template>
			</el-table-column>
		</el-table>
		<!-- 表格内容展示 end -->

		<!-- 表格内容分页组件展示 begin -->
		<el-pagination
			:background="true"
			v-model:current-page="pageNo"
			v-model:page-size="pageSizes"
			:page-sizes="[15, 17, 19, 21]"
			:small="small"
			:disabled="disabled"
			layout=" prev, pager, next, jumper, ->,sizes,total "
			:total="total"
			:prev-icon="DArrowLeft"
			:next-icon="DArrowRight"
			@current-change="getTrademarkList"
			@size-change="sizeChange"
		/>
		<!-- 表格内容分页展示 end -->

		<!-- 添加修改弹出框 begin -->
		<!-- v-model控制Dialog是否显示  -->
		<el-dialog
			v-model="dialogFormVisible"
			:title="tmParams.id ? '修改品牌' : '添加品牌'"
			style="margin-top: 80px"
		>
			<!-- dialog form begin -->
			<el-form
				label-width="100px"
				style="width: 80%"
			>
				<el-form-item label="品牌名称">
					<el-input
						v-model="tmParams.tmName"
						placeholder="填写品牌名称"
					/>
				</el-form-item>
				<!-- 图片上传begin -->
				<el-form-item label="品牌LOGO">
					<el-upload
						class="avatar-uploader"
						action="/app-dev/admin/product/fileUpload"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
					>
						<img
							v-if="tmParams.logoUrl"
							:src="tmParams.logoUrl"
							class="avatar"
						/>
						<el-icon
							v-else
							class="avatar-uploader-icon"
						>
							<UploadFilled />
						</el-icon>
					</el-upload>
				</el-form-item>
				<!-- 图片上传end -->
			</el-form>
			<!-- dialog form end -->
			<!-- dialog 底部取消/确定按钮 begin -->
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogFormVisible = false"
						>取消</el-button
					>
					<el-button
						type="primary"
						@click="save"
					>
						确定
					</el-button>
				</span>
			</template>
			<!-- dialog 底部取消/确定按钮 end -->
		</el-dialog>

		<!-- 添加修改弹出框 end -->
	</el-card>
</template>

<script setup lang="ts">
	import { ElMessage } from 'element-plus';
	//引入icon图标
	import {
		Plus,
		DArrowRight,
		DArrowLeft,
		Edit,
		Delete,
		UploadFilled,
	} from '@element-plus/icons-vue';
	//引入api
	import {
		reqTrademarkList,
		reqAddOrUpdateTrademark,
		reqRemoveTrademark,
	} from '../../../api/product/trademark/index';
	//引入ref响应式数据函数
	import { ref, onMounted, reactive } from 'vue';
	//导入xlsx  导出数据插件
	import * as XLSX from 'xlsx/xlsx.mjs';
	// console.log(XLSX);

	//收集当前页码数据
	let pageNo = ref<number>(1);
	//收集每页多少条数据
	let pageSizes = ref<number>(3);
	//收集数据返回品牌的总个数  已有品牌的数据
	let total = ref<number>(3);
	let records = ref<any>([]);

	//对话框显示/隐藏 响应式数据
	let dialogFormVisible = ref<boolean>(false);

	//添加品牌需要携带的参数
	let tmParams: any = reactive({
		tmName: '',
		logoUrl: '',
	});

	//组件挂载请求一次数据
	onMounted(() => {
		getTrademarkList();
	});
	//获取以有品牌的数据
	const getTrademarkList = async (pager = 1) => {
		//修改当前页码
		pageNo.value = pager;
		//请求服务器数据
		let result = await reqTrademarkList(pageNo.value, pageSizes.value);
		console.log('reqTrademarkLists数据请求:', result);
		//服务器数据回来  替换数据
		records.value = result.records;
		total.value = result.total;
	};

	//分页自定义事件
	//当前页码发生变化的时候触发
	//自定义事件会给父组件返回当前页码
	//此处可以省略  直接分页点击事件调用getTrademarkList
	// const currentHandler = (pager: number) => {
	// 	console.log('点击输出当前页码:', pager);
	// 	getTrademarkList();
	// };
	//每页几条  切换回到第一页 再发请求
	const sizeChange = () => {
		getTrademarkList();
	};

	//导出数据
	const exportData = () => {
		//将JSON数据 变成excel

		//创建插件导出为escel文件需要的格式
		const worksheet = XLSX.utils.json_to_sheet(records.value);
		// console.log(worksheet);
		//创建一个容器
		const workbook = XLSX.utils.book_new();
		//追加数据到容器  准备导出
		XLSX.utils.book_append_sheet(workbook, worksheet);
		//创建文件的标题
		XLSX.utils.sheet_add_aoa(
			worksheet,
			[['序号', '品牌名称', '品牌LOGO']],
			{ origin: 'A1' }
		);
		//导出数据
		XLSX.writeFile(workbook, '品牌名称.xlsx');
	};

	//添加品牌回调
	const addTrademark = () => {
		//点击添加品牌按钮  弹出对话框
		dialogFormVisible.value = true;
		//点击添加品牌按钮 清空对话框表单数据
		tmParams.tmName = '';
		tmParams.logoUrl = '';
		tmParams.id = '';
	};

	//对话框确定按钮回调
	const save = async () => {
		try {
			//新增品牌成功
			await reqAddOrUpdateTrademark(tmParams);
			//隐藏对话框
			dialogFormVisible.value = false;

			//提示信息
			ElMessage({
				type: 'success',
				message: `${tmParams.id ? '修改成功' : '添加成功'}`,
			});
			//重新请求数据
			getTrademarkList(tmParams.id ? pageNo.value : 1);
		} catch (error) {}
	};

	//修改按钮回调
	const UpdateTrademark = (row) => {
		//显示对话框
		dialogFormVisible.value = true;

		//收集已有品牌的数据
		tmParams.tmName = row.tmName;
		tmParams.logoUrl = row.logoUrl;
		tmParams.id = row.id;
	};

	//删除已有品牌
	const removeTradeMark = async (id: number) => {
		console.log(id);
		try {
			await reqRemoveTrademark(id);
			ElMessage({
				type: 'success',
				message: '删除成功',
			});
			getTrademarkList(
				records.value.length > 1 ? pageNo.value : pageNo.value - 1
			);
		} catch (error) {
			ElMessage({
				type: 'error',
				message: '删除失败',
			});
		}
	};

	//图片上传 begin
	// 上传图片成功的钩子
	const handleAvatarSuccess = (response, uploadFile, uploadFiles) => {
		//上传成功请求,返回的服务器数据 response
		//上传文件的信息 uploadFile->顶上file
		//上传文件(批量上传的时候)->uploadFiles
		//收集图片路径
		// imageUrl.value = URL.createObjectURL(uploadFile.raw!);
		tmParams.logoUrl = response.data;
		console.log(tmParams);
	};
	//el-upload组件上传图片的钩子：图片上传之前的钩子
	//上传之前：注入上传文件对象
	//约束文件类型和大小
	const beforeAvatarUpload = (file: any) => {
		console.log(file);
		//约束文件类型
		if (
			file.type == 'image/jpeg' ||
			file.type == 'image/png' ||
			file.type == 'image/gif'
		) {
			if (file.size / 1024 / 1024 < 2) {
				return true;
			}
		} else {
			//提示信息
			ElMessage({
				type: 'error',
				message: '请上传文件类型为：png|jpj|gif且小于2M的图片',
			});
			return false;
		}
		// if (
		// 	rawFile.type !== 'image/jpeg' ||
		// 	rawFile.type !== 'image/png' ||
		// 	rawFile.type !== 'image/gif'
		// ) {
		// 	ElMessage.error('Avatar picture must be JPG format!');
		// 	return false;
		// } else if (rawFile.size / 1024 / 1024 > 2) {
		// 	ElMessage.error('Avatar picture size can not exceed 2MB!');
		// 	return false;
		// }
		// return true;
	};
	//图片上传 end
</script>
<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>
